package netty.proto;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import student.DateType;
import student.Message;
import student.Student;
import student.Worker;

public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    /**
     * 通道就绪
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 发送一个 student 对象
        Message studentMessage = Message.newBuilder()
                .setStudent(Student.newBuilder().setId(1).setName("张三"))
                .setType(DateType.StudentType)
                .build();
        Message workerMessage = Message.newBuilder()
                .setWorker(Worker.newBuilder().setName("王五").setAge(20))
                .setType(DateType.WorkerType)
                .build();
        // 写入消息并刷新缓存
        ctx.writeAndFlush(studentMessage);
        ctx.writeAndFlush(workerMessage);
        System.out.println("消息发送成功");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("服务器: " +ctx.channel().remoteAddress() + " 回复消息: " + msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println(cause.getMessage());
        ctx.close();
    }
}
